package com.dymedia.aibo.app;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import com.dymedia.aibo.BuildConfig;
import com.dymedia.aibo.R;
import com.dymedia.aibo.app.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import me.jessyan.art.utils.DataHelper;
import timber.log.Timber;

public class UpdateApk {
    private Context mContext;
    private Handler mHandler = new Handler();

    public UpdateApk(Context context) {
        mContext = context;
    }

    public void updateNow() {
        Long currTm = System.currentTimeMillis();
        Long lastTm = 0L;
        try {
            lastTm = Long.valueOf(DataHelper.getStringSF(mContext, "updateTime"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (currTm - lastTm > 24 * 60 * 60 * 1000) {
            new Thread(() -> checkApkUpdate((respCode, respObject) -> {
                if (respCode == 200) {
                    DataHelper.setStringSF(mContext, "updateTime", String.valueOf(currTm));
                    updateApk((UpdateApkItem) respObject);
                }
            })).start();
        }
    }

    private class UpdateApkItem {
        String downloadUrl;
        String versionName;
        String detail;
    }

    private void updateApk(UpdateApkItem item) {
        Timber.d("updateApk");
        if (item != null && !item.versionName.equals(BuildConfig.VERSION_NAME) && !item.downloadUrl.isEmpty()) {
            mHandler.post(() -> {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setCancelable(false);
                builder.setTitle(R.string.update_title);
                builder.setMessage(mContext.getString(R.string.update_intro) + item.versionName + "\n" + item.detail);
                builder.setPositiveButton(R.string.update_now, (dialog, which) -> {
                    dialog.dismiss();
                    downloadAPK(item.downloadUrl, "aibo.apk");
                });
                builder.setNegativeButton(R.string.update_late, (dialog, which) -> {
                    dialog.dismiss();
                });
                AlertDialog dialog = builder.create();
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            });
        }
    }

    private void checkApkUpdate(CommonCallback callback) {
        Timber.d("checkApkUpdate");
        URL url;
        BufferedReader bufferedReader = null;
        HttpURLConnection connection = null;
        try {
            String mApkUpdateUrl = String.format("%s%supdate_%s", MainApp.APP_DOMAIN_HTTP, "/aibo/update/", Utils.getCode(mContext));

            url = new URL(mApkUpdateUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuffer = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }

            UpdateApkItem item = new UpdateApkItem();
            JSONObject jsonObj = new JSONObject(stringBuffer.toString());
            item.versionName = jsonObj.optString("VersionName");
            item.detail = "";
            item.downloadUrl = String.format("%s%saibo_%s_%s.apk", MainApp.APP_DOMAIN_HTTP, "/aibo/update/", Utils.getCode(mContext), item.versionName); //aibo_TPLDHEZP_1.2.3.apk
//            if (!TextUtils.isEmpty(item.downloadUrl)) {
//                item.downloadUrl = item.downloadUrl + String.format("aibo_%s_%s.apk", Utils.getCode(mContext), item.versionName);
//            }
            if (jsonObj.has("History")) {
                JSONArray array = jsonObj.getJSONArray("History");
                if (array.length() > 0) {
                    item.detail = array.getJSONObject(0).optString("Detail");
                }
            }
            if (callback != null) {
                callback.resp(200, item);
                return;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        callback.resp(1000, null);
    }

    private long mTaskId;
    private DownloadManager downloadManager;
    private File downloadFile;

    private void downloadAPK(String url, String name) {
        try {
            Timber.d("downloadAPK");
            //downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + name;
            //downloadPath = Environment.getExternalStorageDirectory() + name;
            downloadFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), name);
            downloadFile.delete();

            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            //创建下载任务
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setAllowedOverRoaming(false);//漫游网络是否可以下载

            //设置文件类型，可以在下载结束后自动打开该文件
            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
            String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
            request.setMimeType(mimeString);

            //在通知栏中显示，默认就是显示的
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            request.setVisibleInDownloadsUi(false);
            request.setDestinationUri(Uri.fromFile(downloadFile));

            //sdcard的目录下的download文件夹，必须设置
            //request.setDestinationInExternalPublicDir("/download/", name);

            //将下载请求加入下载队列
            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            //加入下载队列后会给该任务返回一个long型的id，
            //通过该id可以取消任务，重启任务等等，看上面源码中框起来的方法
            mTaskId = downloadManager.enqueue(request);

            //注册广播接收者，监听下载状态
            updateApkReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    checkDownloadStatus();//检查下载状态
                }
            };
            mContext.registerReceiver(updateApkReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private BroadcastReceiver updateApkReceiver = null;

    private void checkDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(mTaskId);//筛选下载任务，传入任务ID，可变参数
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                case DownloadManager.STATUS_PENDING:
                case DownloadManager.STATUS_RUNNING:
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成安装APK
                    installAPK(downloadFile);
                    break;
                case DownloadManager.STATUS_FAILED:
                    Timber.d(">>>下载失败");
                    break;
            }
        }
    }

    //下载到本地后执行安装
    protected void installAPK(File file) {
        if (!file.exists()) return;
        Timber.d("installAPK, file: " + file.getAbsolutePath());
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24) {
            Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            List<ResolveInfo> resInfoList = mContext.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                mContext.grantUriPermission(packageName, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }

            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive");
        }
        //在服务中开启activity必须设置flag,后面解释
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

}
